import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_chip/bean/Order.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/log_util.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/view/goods/order/view_progress.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_chip/widget/keyboard/view_keyboard.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:flutter_chip/widget/widget_paysuccess.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:fsuper/fsuper.dart';
import 'package:provide/provide.dart';
import 'package:tobias/tobias.dart' as tobias;

class OrderInfoPage extends StatefulWidget {
  final String orderId;

  OrderInfoPage(this.orderId);

  @override
  _OrderInfoPageState createState() => _OrderInfoPageState();
}

class _OrderInfoPageState extends StateWithLifecycle<OrderInfoPage> {
  Order order;
  String payType = "-1";
  TextEditingController _contentController = TextEditingController();
  String orderId;
  CancelFunc closeLoading;
  User user;

  @override
  void initState() {
    super.initState();
    fluwx.registerWxApi(
        appId: Comm.WX_APPID,
        universalLink: "https://your.univeral.link.com/placeholder/");
    fluwx.weChatResponseEventHandler.listen((res) {
      print("微信支付errCode：${res.errCode}");
      print("微信支付errStr：${res.errStr}");
      if (res is fluwx.WeChatPaymentResponse) {
        if (res.errCode == 0) {
          String url = "${Api.URL_ORDER_INFO}?orderId=$orderId";
          Http.get(url, successCallBack: (data) {
            Order order = Order.fromJson(json.decode(data));
            Navigator.of(context).push(RouteSlide(
              PaySuccess(
                order.updateAt,
                order.orderId,
                order.payCode,
                "${order.price}",
              ),
            ));
          });
        } else if (res.errCode == -2) {
          Toast.show("支付已取消");
        } else {
          Toast.show("支付失败");
        }
      }
    });
  }

  @override
  void onResume() {
    super.onResume();
    closeLoading = Toast.loading("加载中...");
    _getWalletInfo();
    _getOrder();
  }

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
        titleSpacing: 0.0,
        backgroundColor: Theme.of(context).canvasColor,
        title: Text("订单详情", style: TextStyle(fontSize: 18)),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  _stepWidget(),
                  _moneyWidget(),
                  Divider(indent: 10, endIndent: 10),
                  _expressWidget(),
                  Divider(indent: 10, endIndent: 10),
                  _goodsWidget(),
                  Divider(indent: 10, endIndent: 10),
                  _dataWidget(),
                  _orderWidget(),
                ],
              ),
            ),
            flex: 1,
          ),
          Divider(
            thickness: 0,
            height: 1,
          ),
          _bottomSheet(),
        ],
      ),
    );
  }

  Widget _stepWidget() {
    int status = null != order ? order.status : 0;
    String type = null != order ? order.goodsType : "1";
    return Progress(status, type);
  }

  ///交易金额展示
  Widget _moneyWidget() {
    String price = null != order
        ? "${order.price * order.goodsNum}".replaceAll(".00", "")
        : "";
    String hintText = "";
    int status = null != order && null != order.status ? order.status : 0;
    if (status == 0) {
      hintText = "长时间未付款，订单将自动取消";
    } else if (status == 1) {
      hintText = "等待卖家发货";
    } else if (status == 2) {
      hintText = "卖家已发货";
    }
    return Container(
      height: 100,
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text(
                price,
                style: TextStyle(
                  fontSize: 36,
                  color: Colors.red,
                ),
              ),
              Text(
                "元",
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.red,
                ),
              ),
            ],
          ),
          SizedBox(height: 10),
          Text(
            hintText,
            style: TextStyle(
              fontWeight: FontWeight.w600,
              fontSize: 12,
            ),
          ),
        ],
      ),
    );
  }

  ///快递信息
  Widget _expressWidget() {
    String goodsType = null != order ? order.goodsType : "2";
    String hintText = "暂时无法获取物流信息";
    if (goodsType == "1") {
      hintText = "电子资料线上发货";
    } else {
      hintText = null != order ? order.epName : "暂时无法获取物流信息";
    }
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      height: 48,
      alignment: Alignment.centerLeft,
      child: Row(
        children: <Widget>[
          Text(hintText),
          Expanded(flex: 1, child: Container()),
          FlatButton(
              onPressed: () {},
              child: Text(
                "查看物流",
                style: TextStyle(color: Theme.of(context).accentColor),
              ))
        ],
      ),
    );
  }

  ///商品明细
  Widget _goodsWidget() {
    String picUrl;
    if (null != order && null != order.goodsImg) {
      picUrl = order.goodsImg.split(",").first;
    }
    //图片展示
    Widget _picWidget = Container(
      width: 48,
      child: CachedNetworkImage(
        imageUrl: Api.getUrl(picUrl),
        fit: BoxFit.cover,
        errorWidget: (context, url, error) => CommWidget.imgError(textSize: 10),
      ),
    );
    //描述
    String goodsName = null != order ? order.goodsName : "";
    String goodsNum = null != order ? "数量X${order.goodsNum}" : "数量X1";
    Widget goodsWidget = Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          goodsName,
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            fontWeight: FontWeight.w600,
          ),
        ),
        Text(
          goodsNum,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey,
          ),
        ),
      ],
    );
    return Container(
      height: 84,
      padding: EdgeInsets.all(10),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _picWidget,
          SizedBox(width: 10),
          Expanded(
            flex: 1,
            child: goodsWidget,
          ),
        ],
      ),
    );
  }

  ///资料展示
  Widget _dataWidget() {
    bool show = null != order && order.goodsType == '1';
    String dataLink = '支付成功后展示';
    if (null != order &&
        (order.status == 1 || order.status == 2 || order.status == 3)) {
      dataLink = order.dataLink ?? "";
    }
    if (null != order && Comm.userId == order.sellerId) {
      dataLink = order.dataLink ?? "";
    }
    return Offstage(
      offstage: !show,
      child: Container(
        margin: EdgeInsets.only(left: 10, right: 10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "资料托管地址：",
              style: TextStyle(color: Colors.grey),
            ),
            FSuper(
              text: dataLink,
              textAlign: TextAlign.start,
              textAlignment: Alignment.centerLeft,
              padding: EdgeInsets.only(left: 10, right: 28),
              child1: Text(
                "复制",
                style: TextStyle(
                  color: Theme.of(context).accentColor,
                  fontWeight: FontWeight.w600,
                ),
              ),
              textColor: Colors.redAccent,
              child1Alignment: Alignment.centerRight,
              onChild1Click: () {
                if (null != order &&
                    (order.status == 1 ||
                        order.status == 2 ||
                        order.status == 3)) {
                  if (null != order.dataLink && order.dataLink != "") {
                    Clipboard.setData(ClipboardData(text: order.dataLink));
                    Toast.show("复制成功");
                  }
                }
              },
            ),
            Divider(),
          ],
        ),
      ),
    );
  }

  ///订单底部信息
  Widget _orderWidget() {
    TextStyle style = TextStyle(fontSize: 12, color: Color(0xFF666666));
    String payCode =
        null != order && null != order.payCode ? order.payCode : "";
    bool isBuyer = null != order ? order.buyerId == Comm.userId : true;
    String nickName = null != order ? order.buyerName : "";
    if (isBuyer) {
      nickName = null != order ? order.sellerName : "";
    }
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: <Widget>[
              Text(isBuyer ? "卖家昵称" : "买家昵称", style: style),
              Expanded(flex: 1, child: Container()),
              Text(nickName, style: style),
            ],
          ),
          SizedBox(height: 10),
          Row(
            children: <Widget>[
              Text("订单编号", style: style),
              Expanded(flex: 1, child: Container()),
              Text(null == order ? "" : order.orderId, style: style),
            ],
          ),
          Offstage(
            offstage: null == order || null == order.payCode,
            child: SizedBox(height: 10),
          ),
          Offstage(
            offstage: null == order || null == order.payCode,
            child: Row(
              children: <Widget>[
                Text("交易单号", style: style),
                Expanded(flex: 1, child: Container()),
                Text(payCode, style: style),
              ],
            ),
          ),
          SizedBox(height: 10),
          Row(
            children: <Widget>[
              Text("交易时间", style: style),
              Expanded(flex: 1, child: Container()),
              Text(null == order ? "" : order.createAt, style: style),
            ],
          ),
        ],
      ),
    );
  }

  ///底部悬浮按钮
  Widget _bottomSheet() {
    int status = null != order ? order.status : 0;
    bool isBuyer = null != order ? order.buyerId == Comm.userId : true;
    String hint = "";
    if (status == 1) {
      hint = isBuyer ? "提醒发货" : "发货";
    } else if (status == 2) {
      hint = isBuyer ? "确认收货" : "提醒收货";
    } else if (status == 6) {
      hint = "删除订单";
    } else {
      hint = isBuyer ? "评价" : "";
      if (isBuyer) {
        if (null != order && order.tradeGrade == null && status != 0) {
          hint = "评价";
        } else {
          hint = "";
        }
      }
    }
    Widget _btnWidget = Offstage(
      offstage: "" == hint,
      child: GestureDetector(
        child: Container(
          height: 30,
          width: 84,
          child: Text(hint),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              border: Border.all(color: Color(0xffcccccc), width: 1),
              borderRadius: BorderRadius.circular(20)),
        ),
        onTap: () {
          if (hint == "评价" || (hint == "发货" && order.goodsType == '1')) {
            _showDialog(context, hint);
          } else if (hint == "提醒发货") {
            _setStatus(11, null);
          } else if (hint == "提醒收货") {
            _setStatus(12, null);
          } else if (hint == "确认收货") {
            _setStatus(3, null);
          }
        },
      ),
    );

    return Container(
      width: Comm.screenWidth,
      height: 49,
      alignment: Alignment.center,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(child: Container()),
          Offstage(
            offstage: null != order && status == 0 && hint == "",
            child: _btnWidget,
          ),
          SizedBox(width: 10),
          Offstage(
            offstage: null != order && status != 0,
            child: Container(
              width: 80,
              height: 48,
              color: Colors.deepOrange,
              child: FlatButton(
                onPressed: () {
                  showPayTypeDialog();
                },
                child: Text(
                  '付款',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  List pay = [
    {
      "name": "账户余额",
      "type": "00",
      "icon": Icons.account_balance_wallet,
      "color": Colors.orangeAccent,
    },
    {
      "name": "支付宝",
      "type": "01",
      "icon": FontAwesomeIcons.alipay,
      "color": Color(0XFF00A1E9),
    },
    {
      "name": "微信",
      "type": "02",
      "icon": FontAwesomeIcons.weixin,
      "color": Color(0XFF01D00E),
    },
  ];

  showPayTypeDialog() {
    return showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("请选择支付方式"),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: pay.map((data) {
                return FSuper(
                  width: double.infinity,
                  height: 56,
                  text: data['name'],
                  textSize: 16,
                  textWeight: FontWeight.w600,
                  padding: EdgeInsets.only(left: 36),
                  textAlignment: Alignment.centerLeft,
                  child1: Icon(data['icon'], color: data['color']),
                  child1Alignment: Alignment.centerLeft,
                  child2:
                      data['type'] != '00' ? Text('') : Text("(剩余:￥$money)"),
                  child2Margin: EdgeInsets.only(left: 36),
                  onClick: () {
                    payType = data['type'];
                    LogUtil.v("支付类型：$payType");
                    if (payType == '00') {
                      if (double.parse(money) == 0.0) {
                        Toast.show("账户余额不足");
                        return;
                      }
                      Navigator.pop(context);
                      _showPwdBoard();
                    } else {
                      Navigator.pop(context);
                      payFor();
                    }
                  },
                );
              }).toList(),
            ),
          );
        });
  }

  ///评价&发货
  void _showDialog(BuildContext context, String title) {
    if (null == order) {
      Toast.show("未获取到订单");
      return;
    }
    String hint = "发货" == title ? "请输入资料托管地址" : "请输入评价内容";
    int level = 5;
    //底部按钮
    Widget _topBtnWidget = Row(
      children: <Widget>[
        GestureDetector(
          onTap: () {
            Navigator.of(context).pop();
          },
          child: Container(
            alignment: Alignment.center,
            child: Text(
              "取消",
              style: TextStyle(color: Theme.of(context).accentColor),
            ),
            height: 40,
            width: 120,
          ),
        ),
        Expanded(flex: 1, child: Container()),
        GestureDetector(
          onTap: () {
            if (_contentController.text.isEmpty) {
              Toast.show("内容不能为空");
              return;
            }
            Navigator.of(context).pop();
            Map<String, String> map = Map();
            int status;
            if ("发货" == title) {
              status = 2;
              map["dataLink"] = _contentController.text;
            } else {
              status = 7;
              map["tradeLevel"] = "$level";
              map["tradeGrade"] = _contentController.text;
            }
            _setStatus(status, map);
          },
          child: Container(
            alignment: Alignment.center,
            child: Text(
              "提交",
              style: TextStyle(color: Theme.of(context).accentColor),
            ),
            width: 120,
            height: 40,
          ),
        ),
      ],
    );
    Widget _inputWidget = Container(
      margin: EdgeInsets.only(left: 20, right: 20, top: 6, bottom: 16),
      child: TextField(
        maxLength: 200,
        maxLines: 4,
        textAlign: TextAlign.start,
        controller: _contentController,
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(top: 10),
          hintText: hint,
          hintStyle: TextStyle(color: Colors.grey, fontSize: 16),
          border: InputBorder.none,
        ),
      ),
    );
    showDialog(
        context: context,
        builder: (context) {
          return StatefulBuilder(
            builder: (context, state) {
              return SimpleDialog(
                title: Text(title),
                children: <Widget>[
                  Offstage(
                    offstage: "发货" == title,
                    child: Row(
                      children: [1, 2, 3, 4, 5].map((item) {
                        Icon icon = Icon(Icons.star, color: Colors.amberAccent);
                        icon = Icon(Icons.star, color: Colors.amberAccent);
                        if (item <= level) {
                        } else {
                          icon = Icon(Icons.star_border,
                              color: Colors.amberAccent);
                        }
                        return IconButton(
                            icon: icon,
                            onPressed: () {
                              state(() {
                                level = item;
                              });
                            });
                      }).toList(),
                    ),
                  ),
                  _inputWidget,
                  _topBtnWidget,
                ],
              );
            },
          );
        });
  }

  ///获取订单详情
  void _getOrder() async {
    String url = "${Api.URL_ORDER_INFO}?orderId=${widget.orderId}";
    Http.get(url, successCallBack: (data) {
      if (null != closeLoading) {
        closeLoading();
      }
      setState(() {
        order = Order.fromJson(json.decode(data));
      });
    }, errorCallBack: (errorMsg) {
      if (null != closeLoading) {
        closeLoading();
      }
      Toast.show(errorMsg);
    });
  }

  String money;

  ///钱包信息
  void _getWalletInfo() {
    Http.get(Api.URL_WALLET_INFO, successCallBack: (data) {
      setState(() {
        money = "${json.decode(data)["availMoney"]}";
      });
    });
  }

  ///订单操作
  void _setStatus(int status, Map<String, String> map) {
    if (null == order) {
      Toast.show("未获取到订单");
      return;
    }
    closeLoading = Toast.loading("操作中...");
    Map<String, String> params = Map();
    if (null != map) {
      params.addAll(map);
    }
    params["orderId"] = order.orderId;
    params["status"] = "$status";
    Http.post(Api.URL_ORDER_STATUS, params: params, successCallBack: (data) {
      if (null != closeLoading) {
        closeLoading();
      }
      setState(() {
        order = Order.fromJson(json.decode(data));
      });
    }, errorCallBack: (error) {
      Toast.show(error);
      if (null != closeLoading) {
        closeLoading();
      }
    });
  }

  ///吊起支付
  void payFor() async {
    if (null == order) {
      Toast.show("获取订单失败");
      return;
    }
    closeLoading = Toast.loading("支付中...");
    Map<String, String> params = Map();
    params["orderId"] = order.orderId;
    params["num"] = "${order.goodsNum}";
    params["payType"] = "$payType";
    Http.post(Api.URL_ORDER_PAYINFO, params: params,
        successCallBack: (data) async {
      if (null != closeLoading) {
        closeLoading();
      }
      Order payInfo = Order.fromJson(json.decode(data));
      if (payType == "01") {
        var result = await tobias.aliPay(payInfo.orderInfo,
            evn: tobias.AliPayEvn.ONLINE);
        Map<String, dynamic> payResult = jsonDecode(json.encode(result));

        print("订单结果：$payResult");
        if (int.parse(payResult['resultStatus']) == 9000) {
          print('支付成功');
          var payInfo =
              json.decode(payResult['result'])['alipay_trade_app_pay_response'];
          print('payinfo=$payInfo');
          Navigator.of(context).push(RouteSlide(
            PaySuccess(
              payInfo['timestamp'],
              payInfo['out_trade_no'],
              payInfo['trade_no'],
              payInfo['total_amount'],
            ),
          ));
        } else if (int.parse(payResult['resultStatus']) == 6001) {
          Toast.show("支付取消");
        } else {
          Toast.show(payResult['memo']);
        }
      } else if (payType == '02') {
        var wxPay = json.decode(payInfo.orderInfo);
        orderId = payInfo.orderId;
        fluwx.payWithWeChat(
          appId: wxPay['appid'],
          partnerId: wxPay['partnerid'],
          prepayId: wxPay['prepayid'],
          packageValue: wxPay['package'],
          nonceStr: wxPay['noncestr'],
          timeStamp: int.parse(wxPay['timestamp']),
          sign: wxPay['sign'],
        );
      } else {
        //余额支付
        Navigator.of(context).push(RouteSlide(
          PaySuccess(
            payInfo.createAt,
            payInfo.orderId,
            payInfo.payCode,
            "${payInfo.price}",
          ),
        ));
      }
    }, errorCallBack: (error) {
      Toast.show(error);
      if (null != closeLoading) {
        closeLoading();
      }
    });
  }

  ///校验密码
  void _showPwdBoard() {
    if ("-1".endsWith(payType)) {
      Toast.show("请选择到账账户");
      return;
    }
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (builder) {
        return CustomKeyboard(
          autoBack: true,
          onClose: () {
            Navigator.pop(context);
          },
          onForget: () {
            Routers.router.navigateTo(context,
                "${Routers.PAGE_CHECKPHONE}?title=bdzf&phone=${user.phone}",
                transition: TransitionType.inFromRight);
          },
          onReset: () {
            Routers.router.navigateTo(context,
                "${Routers.PAGE_CHECKPHONE}?title=xgzf&phone=${user.phone}",
                transition: TransitionType.inFromRight);
          },
          onResult: (data) {
            CancelFunc cancelFunc = Toast.loading("正在校验...");
            String pwd = data.toString().trim();
            Map<String, String> params = Map();
            params["pwd"] = pwd;
            Http.post(Api.URL_WALLET_PWD, params: params,
                successCallBack: (data) {
              Navigator.pop(context);
              cancelFunc();
              payFor();
            }, errorCallBack: (error) {
              Navigator.pop(context);
              cancelFunc();
              if ("未设置交易密码" == error) {
                _setPwdDialog();
                return;
              }
              Toast.show(error);
            });
          },
        );
      },
    );
  }

  void _setPwdDialog() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("温馨提示"),
            content: Text("您尚未设置交易密码，是否去设置？"),
            actions: <Widget>[
              FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                },
                child: Text("取消"),
              ),
              FlatButton(
                onPressed: () {
                  Navigator.pop(context);
                  if (null != user && null == user.phone) {
                    Toast.show("请先绑定手机号");
                    return;
                  }
                  Routers.router.navigateTo(context,
                      "${Routers.PAGE_CHECKPHONE}?title=bdzf&phone=${user.phone}",
                      transition: TransitionType.inFromRight);
                },
                child: Text("去设置"),
              ),
            ],
          );
        });
  }
}
